package com.dman.multi.cmd;

import org.apache.pivot.collections.List;
import org.apache.pivot.util.Vote;
import org.apache.pivot.wtk.Alert;
import org.apache.pivot.wtk.Dialog;
import org.apache.pivot.wtk.DialogStateListener;
import org.apache.pivot.wtk.MessageType;
import org.apache.pivot.wtk.Prompt;

import com.dman.multi.core.Download;
import com.dman.multi.ui.DMan;

public class GUIDeleteCommand implements Command {

	private DMan parent;
	private List<Download> downloadList;
	private Alert alert;

	public GUIDeleteCommand(DMan prnt, List<Download> dList) {
		this.parent = prnt;
		this.downloadList = dList;
		alert = new Alert(MessageType.QUESTION, "Are you sure to delete the selected download?", null);
		Alert.OptionSequence opseq = alert.getOptions();	
		opseq.remove(0, opseq.getLength());
		opseq.add("Yes");
		opseq.add("No");
		alert.setModal(true);
		alert.getDialogStateListeners().add(new DialogStateListener.Adapter(){
			@Override
			public Vote previewDialogClose(Dialog dialog, boolean result) {
				int index = alert.getSelectedOptionIndex();
				if(index < 1){
					index = parent.getSelectedTableViewIndex();
					if(index >= 0){
						synchronized (downloadList) {
							Download d = downloadList.get(index);
							downloadList.remove(d);
							try {
								d.delete();
							} catch (Exception e) {
								Prompt.prompt("Unable to delete download", parent);
							}			
						}
					}
				}
				
				return Vote.APPROVE;
			}
		});
	}
	
	@Override
	public void execute() {
		alert.open(parent);		
	}

}
